package com.winchain.provider;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.base.utils.SystemUtil.SystemMode;
import com.shell.feign.PubParameterFeign;
import com.shell.framework.utils.MessageSender;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.message.keyword.PrepymtBatchKeyword;
import com.shell.governor.modules.message.keyword.TmoutRemindKeyword;
import com.shell.governor.modules.vo.ParameterVo;
import com.winchain.basic.exception.ExtException;
import com.winchain.chainbill.bill.base.service.CbRecService;
import com.winchain.chainbill.bill.biz.query.vo.CbRecVo;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TimeoutRemindExtProvider {
	@Autowired
	private CbRecService cbRecService;
	@Autowired
	private PubParameterFeign pubParameterFeign;
	private Log logger = LogFactory.getLog(getClass());

	@RequestMapping({ "/timeoutRemind/batchJob" })
	public void rcvTmoutRemindBatchJob(@RequestParam("workDate") String workDate) {
		this.logger.info("--------rcvTmoutRemindBatchJob excute start--------");
		if (!SystemUtil.SystemMode.prod.equals(SystemUtil.getSystemMode())) {
			ParameterVo parameter = this.pubParameterFeign.getCommonParameter("SYS_DATE_CONF");
			if ((parameter != null) && (!StringUtil.emptyAndNull(parameter.getParmValue()))) {
				workDate = parameter.getParmValue();
			}
		}
		this.logger.info("--------workDate is " + workDate + "--------");
		try {
			boolean exFlag = false;
			int successNo4Tt = 0;
			int successNo4Exp = 0;

			List<CbRecVo> cbRecList = getCbRecsForTimeout(workDate);
			this.logger.info("[timeout remind] message size is " + cbRecList.size());
			CbRecVo cbRec;
			for (Iterator localIterator = cbRecList.iterator(); localIterator.hasNext();) {
				cbRec = (CbRecVo) localIterator.next();
				try {
					boolean sendSuful = false;
					sendSuful = sendSMSForTimeout(cbRec);
					if (sendSuful) {
						successNo4Tt += 1;
					} else {
						exFlag = true;
					}
				} catch (Exception e) {
					exFlag = true;
					e.printStackTrace();
					this.logger.error("rcvTmoutRemindBatchJob excute error!", e);
				}
			}
			List<CbRecVo> expCbRecList = getCbRecsForExpiredOneDay(workDate);
			this.logger.info("[expired bill] size is " + cbRecList.size());
			for (CbRecVo cbRec2 : expCbRecList) {
				try {
					boolean sendSuful = false;
					sendSuful = sendSysMessageForExpired(cbRec2, cbRec2.getBuyerId(), "MT03101");

					sendSuful = sendSMSForExpired(cbRec2, cbRec2.getBuyerId(), sendSuful, "MT02610");
					if (sendSuful) {
						successNo4Exp += 1;
					} else {
						exFlag = true;
					}
				} catch (Exception e) {
					exFlag = true;
					e.printStackTrace();
					this.logger.error("rcvTmoutRemindBatchJob excute error!", e);
				}
			}
			this.logger.info("exFlag:" + exFlag + " successNo4Tt:" + successNo4Tt + " successNo4Exp:" + successNo4Exp);
			if (exFlag) {
				throw new ExtException("����������������������������������/������������������");
			}
			expCbRecList = getCbRecsForExpiredThreeDay(workDate);
			this.logger.info("[expired bill] size is " + cbRecList.size());
			for (CbRecVo cbRec2 : expCbRecList) {
				try {
					boolean sendSuful = false;
					sendSuful = sendSysMessageForExpired(cbRec2, cbRec2.getBuyerId(), "MT03102");

					sendSuful = sendSMSForExpired(cbRec2, cbRec2.getBuyerId(), sendSuful, "MT02611");
					if (sendSuful) {
						successNo4Exp += 1;
					} else {
						exFlag = true;
					}
				} catch (Exception e) {
					exFlag = true;
					e.printStackTrace();
					this.logger.error("rcvTmoutRemindBatchJob excute error!", e);
				}
			}
			this.logger.info("exFlag:" + exFlag + " successNo4Tt:" + successNo4Tt + " successNo4Exp:" + successNo4Exp);
			if (exFlag) {
				throw new ExtException("����������������������������������/������������������");
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error("��������/������������������������", e);
			throw new ExtException(e.getMessage());
		}
		this.logger.info("--------rcvTmoutRemindBatchJob excute end--------");
	}

	private List<CbRecVo> getCbRecsForTimeout(String workDate) {
		String theDayBefore = "";
		String sevenDaysAgo = "";
		String threeDaysLater = "";
		String oneDayAfter = "";
		try {
			theDayBefore = DateUtil.parseDate(DateUtil.getPreDay(workDate, -1), "yyyyMMdd", "yyyy-MM-dd");
			theDayBefore = StringUtil.getParameterLike(theDayBefore);
			sevenDaysAgo = DateUtil.parseDate(DateUtil.getPreDay(workDate, -7), "yyyyMMdd", "yyyy-MM-dd");
			sevenDaysAgo = StringUtil.getParameterLike(sevenDaysAgo);
			threeDaysLater = DateUtil.dateCalculate(workDate, "yyyyMMdd", 0, 0, 3);
			oneDayAfter = DateUtil.dateCalculate(workDate, "yyyyMMdd", 0, 0, 1);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new ExtException("��������������");
		}
		List<CbRecVo> cbRecList = this.cbRecService.selectBillForTimeOut(theDayBefore, sevenDaysAgo, threeDaysLater,
				oneDayAfter);
		return cbRecList;
	}

	private boolean sendSMSForTimeout(CbRecVo cbRec) {
		boolean sendSuful = false;
		PrepymtBatchKeyword smskeyWord = getPrepymtBatchKeyword(cbRec);
		String smsTemplateId = "MT02609";
		try {
			MessageSender.sendMessageByTmpl("", smsTemplateId, smskeyWord, cbRec.getSellerId());
			sendSuful = true;
			this.logger.info("[timeout remind] phone message send successful, billCode is " + cbRec.getBillCode());
		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error("�������������������������� ", e);
		}
		return sendSuful;
	}

	private List<CbRecVo> getCbRecsForExpiredOneDay(String workDate) {
		String expireDate = "";
		try {
			expireDate = DateUtil.getPreDay(workDate, 1);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new ExtException("������������");
		}
		return getCbRecsForExpired(expireDate);
	}

	private List<CbRecVo> getCbRecsForExpiredThreeDay(String workDate) {
		String expireDate = "";
		try {
			expireDate = DateUtil.getPreDay(workDate, 3);
		} catch (ParseException e) {
			e.printStackTrace();
			throw new ExtException("������������");
		}
		return getCbRecsForExpired(expireDate);
	}

	private List<CbRecVo> getCbRecsForExpired(String expireDate) {
		List<String> stateList = new ArrayList();
		stateList.add("S001");
		stateList.add("S002");
		stateList.add("S003");
		stateList.add("S024");
		stateList.add("S027");
		stateList.add("S028");
		stateList.add("S004");
		stateList.add("S018");
		List<CbRecVo> cbRecList = this.cbRecService.selectBillsByExpireDate(expireDate, stateList);
		return cbRecList;
	}

	private boolean sendSysMessageForExpired(CbRecVo cbRec, String cusId, String templateId) {
		boolean sendSuful = false;
		TmoutRemindKeyword keyWord = getTmoutRemindKeyword(cbRec);
		try {
			MessageSender.sendMessageByTmpl("", templateId, keyWord, cusId);
			sendSuful = true;
		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error("������������������������������ ", e);
		}
		return sendSuful;
	}

	private boolean sendSMSForExpired(CbRecVo cbRec, String cusId, boolean sdSYSFlag, String smsTemplateId) {
		boolean sendSuful = false;
		TmoutRemindKeyword smskeyWord = getTmoutRemindKeyword(cbRec);
		try {
			MessageSender.sendMessageByTmpl("", smsTemplateId, smskeyWord, cusId);
			if (sdSYSFlag) {
				sendSuful = true;
			}
		} catch (Exception se) {
			se.printStackTrace();
			this.logger.error("�������������������������� ", se);
		}
		return sendSuful;
	}

	private PrepymtBatchKeyword getPrepymtBatchKeyword(CbRecVo cbRec) {
		PrepymtBatchKeyword keyWord = new PrepymtBatchKeyword();
		keyWord.setBuyerNm(cbRec.getBuyerNm());
		BigDecimal billAmt = cbRec.getBillAmt();

		keyWord.setBillAmt(billAmt.toString());
		String expDate = SysDateUtil.parseDate(cbRec.getExpDate(), "yyyyMMdd", "yyyy-MM-dd");
		String sndDate = cbRec.getSndDate();
		keyWord.setExpDate(expDate);
		keyWord.setSndDate(sndDate);
		keyWord.setWebsite(SpringContextUtil.getProperty("chainbill.website"));

		return keyWord;
	}

	private TmoutRemindKeyword getTmoutRemindKeyword(CbRecVo cbRec) {
		TmoutRemindKeyword keyWord = new TmoutRemindKeyword();
		BigDecimal billAmt = cbRec.getBillAmt();

		keyWord.setBillAmt(billAmt.toString());
		keyWord.setAcctNo(cbRec.getAcctNo());
		keyWord.setPhoneNo(SpringContextUtil.getProperty("phoneNo"));
		return keyWord;
	}
}
